/* eslint-disable */

import indexConfig from '@/config/index.config';
import {
// 支付宝h5支付
	toaliwappay ,
// 获取微信公众号支付
	wechatofficialaccountpayparm ,
// 获取微信H5支付参数
	wechath5payparm ,recharge_toalipagepay,recharge_wechatqrpayparm
} from '@/api/basic';
// import jweixin from '@/common/jweixin';

import {querybaseinfoset,
	//APP支付宝支付
	aliPay ,
// 支付宝pc支付
	toalipagepay ,
// 获取微信小程序支付
	wechatappletpay ,
// APP微信支付
	wxpay} from '@/api/basic';
import {isBindingCheck} from '@/api/login';
import {http} from '@/utils/request';
import mHelper from '@/utils/helper';
import mRouter from '@/utils/router';
import {toprepay,} from '@/api/product';
import console from "@dcloudio/uni-h5/src/core/helpers/console";

export default {
	// 判断是否公众号（微信H5）
	isWechat() {
		// #ifdef H5
		const ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {
			return false;
		}
		// #endif
	},

	// wxjssdk
	async wxConfigH5(url) {
		if (this.isWechat()) {
			const jsApiList = JSON.stringify([
				'chooseWXPay',
				'scanQRCode',
				'updateAppMessageShareData',
				'updateTimelineShareData'
			]);
			await http
				.post(`${wechatConfig}`, {
					url: url,
					jsApiList, // 需要调用微信的原生方法
					debug: true // 是否打开调试
				})
				.then(r => {
					jweixin.config({
						...r
					});
				});
		}
	},
	checkWXJSBridge(data) {
		let that = this
		let interval = setInterval(() => {
			if (typeof window.WeixinJSBridge != 'undefined') {
				clearTimeout(interval)
				that.onBridgeReady(data)
			}
		}, 200)
	},

	onBridgeReady(data) {
		console.log(data)
		var _this = this
		window.WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				appId: data.appid, // 公众号名称，由商户传入
				timeStamp: data.time_stamp, // 时间戳，自1970年以来的秒数
				nonceStr: data.nonce_str, // 随机串
				package: data.package_,
				signType: data.sign_type, // 微信签名方式：
				paySign: data.pay_sign // 微信签名
			},
			function(res) {
				console.log(res)
				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					_this.$mHelper.toast('支付成功')
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					_this.$mHelper.toast('取消支付')
				} else {
					_this.$mHelper.toast('支付失败')
				}
				setTimeout(() => {
					_this.$common.redirectTo(
						'/pages/user/money/sucess?id=' + data.payment_id
					)
				}, 1000)
			}
		)
	},
	/*
	 *@des 微信支付
	 *
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async weixinPay(order_group, data, route = '/pages/user/money/success', code) {

		let url='';
		// #ifdef H5
		if (this.isWechat()) {//TODO
			url=`${wechatofficialaccountpayparm}`;
		}else{
			url=`${wechath5payparm}`;
		}
		// #endif
		// #ifdef APP-PLUS
		  url=`${wxpay}`;
		// #endif
		// #ifdef MP-WEIXIN
			url=`${wechatappletpay}`;
		// #endif

		// #ifdef APP-PLUS
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				storeId:indexConfig.storeId,
				trade_type: 'app',
				data
			})
			.then(r => {
				uni.requestPayment({
					provider: 'wxpay', // 微信支付
					orderInfo: JSON.stringify(r.data), //微信订单数据 r.config
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {
						console.log('err', err);
						mHelper.toast('支付已取消');
					}
				});
			});
		// #endif
		// #ifdef MP-WEIXIN
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'mini_program',
				orderCode:data.orderCode,
				storeId:indexConfig.storeId,
				orderId:data.orderId,
				orderType: data.orderType,
				type:data.type,
			})
			.then(r => {
				console.log(r)
				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-3){
					mHelper.toast('没有待支付订单');
					return false;
				}
				if(r.flag==-9){
					mHelper.toast('没开启');
					return false;
				}
				if(r.flag==-8){
					mHelper.toast('参数错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				uni.requestPayment({
					provider: 'wxpay',
					nonceStr: r.data.nonce_str,
					package: r.data.package_,
					signType: r.data.sign_type,
					paySign: r.data.pay_sign,
					timeStamp: r.data.time_stamp,
					success: () => {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: res => {
						console.log(res)

					},
					complete: () => {
					}
				});

			});
		// #endif
		// #ifdef H5
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'js',
				storeId:indexConfig.storeId,
				orderCode:data.orderCode,
				orderId:data.orderId,
				orderType: data.orderType,
				type:data.type,
				//	openid: res.data.openid
			})
			.then(r => {
				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-3){
					mHelper.toast('没有待支付订单');
					return false;
				}
				if(r.flag==-9){
					mHelper.toast('没开启');
					return false;
				}
				if(r.flag==-8){
					mHelper.toast('参数错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				if (this.isWechat()) {
					if (r) {
						this.checkWXJSBridge(r.data)
					}else{
						window.location.href = r.msg
						return;
					}
				}else{
					mHelper.toast(r.mwebUrl);
					console.log(r.mwebUrl)
					location.href=r.mwebUrl
				}

			});
		// #endif


	},


	/*
	 *@des 支付宝支付
	 *
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async aliPay(order_group, data, route = '/pages/user/money/success') {

		// #ifdef MP-QQ
		mHelper.toast('QQ小程序不支持支付宝充值');
		return;
		// #endif
		// #ifdef MP-WEIXIN
		mHelper.toast('微信小程序不支持支付宝充值');
		return;
		// #endif

		let url='';
		// #ifdef H5
		url=`${toaliwappay}`;
			// #endif
			// #ifdef APP-PLUS
		url=`${aliPay}`;
			// #endif
		await http
			.get(url, {
				orderCode:data.orderCode,
				orderId:11,
				storeId:indexConfig.storeId,
				orderType: 1,
				type:data.type,
				// #ifdef H5
				trade_type: 'wap',
				// #endif
				// #ifdef APP-PLUS
				trade_type: 'app',
				// #endif

			})
			.then(r => {

				// #ifdef H5
				if (r) {
					let divDom = document.createElement('div')
					divDom.innerHTML = r.data;
					document.body.appendChild(divDom)

					let testForm = document.getElementsByName('punchout_form')
					testForm[0].dispatchEvent(new Event('submit'))
					testForm[0].submit()
					document.body.removeChild(testForm[0])

				}
			//	window.location.href = r;
				// #endif
				// #ifdef APP-PLUS
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: r, //微信、支付宝订单数据
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {
						console.log(err)
						mHelper.toast('支付已取消');
					}
				});
				// #endif
			});
	},

	/*
	 *@des 余额支付
	 *
	 *@param data 支付参数
	 */
	async balancePay(data, route = '/pages/set/pay/setPassword?type=1') {
		data.storeId=indexConfig.storeId;
		await http
			.post(`${toprepay}`, data)
			.then(r => {
				// -1:用户不存在 -2:支付密码错误 -3:没有待支付的订单 -4:用户预存款金额不足 -6:没有设置支付密码 1 成功
				if (-1 == r) {
					mHelper.toast('用户不存在');
				} else if (-2 == r) {
					mHelper.toast('支付密码错误');
				} else if (-3 == r) {
					mHelper.toast('没有待支付的订单');
				} else if (-4 == r) {
					mHelper.toast('用户预存款金额不足');
				} else if (-6 == r) {
					mHelper.toast('没有设置支付密码');
				} else if (1 == r) {
					mRouter.redirectTo({route});
				}

			});
	},
	/*
	 *@des 微信支付
	 * type 1 公众号 2 h5 3 小程序 4 app 5 pc
	 *@param order_group 订单:order;充值:recharge;
	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
	 */
	async weixinRecharge(order_group, data, route = '/pages/user/money/success', code) {
		let url=`${recharge_wechatqrpayparm}`;
		let type=3;
		// #ifdef H5
		if (this.isWechat()) {//TODO
			type=1;
		}else{
			type=2;
		}
		// #endif
		// #ifdef APP-PLUS
		type=4;
		// #endif

		// #ifdef APP-PLUS
		await http
			.get(url, {
				order_group,
				type: type,
				storeId:indexConfig.storeId,
				money:data.money,
				trade_type: 'app',
				data
			})
			.then(r => {
				uni.requestPayment({
					provider: 'wxpay', // 微信支付
					orderInfo: JSON.stringify(r.data), //微信订单数据 r.config
					success: function () {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: function (err) {
						console.log('err', err);
						mHelper.toast('支付已取消');
					}
				});
			});
		// #endif
		// #ifdef MP-WEIXIN
		await http
			.get(url, {
				type: type,
				trade_type: 'mini_program',
				storeId:indexConfig.storeId,
				money:data.money

			})
			.then(r => {
				console.log(r)
				if(r.flag==-10){
					mHelper.toast('请绑定微信');
					mRouter.push({
						route: '/pages/public/auth'
					});
					return false;
				}
				if(r.flag==-5){
					mHelper.toast('微信生成预支付信息错误');
					return false;
				}
				if(r.flag==-11){
					mHelper.toast('请绑定手机号');
					mRouter.push({
						route: '/pages/public/bindMobile'
					});
					return false;
				}
				uni.requestPayment({
					provider: 'wxpay',
					nonceStr: r.nonce_str,
					package: r.package_,
					signType: r.sign_type,
					paySign: r.pay_sign,
					timeStamp: r.time_stamp,
					success: () => {
						mHelper.toast('支付成功');
						mRouter.redirectTo({route});
					},
					fail: res => {
						console.log(res)

					},
					complete: () => {
					}
				});

			});
		// #endif
		// #ifdef H5
		await http
			.get(url, {
				order_group,
				pay_type: 1,
				trade_type: 'js',
				money:data.money,
				storeId:indexConfig.storeId,
				orderCode:data.orderCode,
				orderId:data.orderId,
				orderType: data.orderType,
				type: type,
				//	openid: res.data.openid
			})
			.then(r => {
				console.log(r)
				location.href=r.mwebUrl
				jweixin.ready(() => {
					console.log(r.data.mwebUrl)
					location.href=r.data.mwebUrl
					jweixin.chooseWXPay({
						...r.data.mwebUrl,
						success() {
							mHelper.toast('支付成功');
							mRouter.redirectTo({route});
						},
						fail(res) {
							// 支付成功后的回调函数
							mHelper.toast('支付已取消');
						}
					});
				});

			});
		// #endif


	},
	/*
    	 *@des 支付宝充值
    	 *
    	 *@param order_group 订单:order;充值:recharge;
    	 2 h5  4 app 5 pc
    	 *@param data 订单 {“order_id”:199} 充值 {“money”:100};
    	 */
    	async aliPayRecharge(order_group, data, route = '/pages/user/money/success') {

    		// #ifdef MP-QQ
    		mHelper.toast('QQ小程序不支持支付宝充值');
    		return;
    		// #endif
    		// #ifdef MP-WEIXIN
    		mHelper.toast('微信小程序不支持支付宝充值');
    		return;
    		// #endif
    	let type=2;
    		let url=`${recharge_toalipagepay}`;
    		// #ifdef H5
    		 type=2;
    			// #endif
    			// #ifdef APP-PLUS
    		 type=4;
    			// #endif
    		await http
    			.get(url, {
    				storeId:indexConfig.storeId,
    				money:data.money,
    				type:type,
    				// #ifdef H5
    				trade_type: 'wap',
    				// #endif
    				// #ifdef APP-PLUS
    				trade_type: 'app',
    				// #endif

    			})
    			.then(r => {

    				// #ifdef H5
    				if (r) {
    					let divDom = document.createElement('div')
    					divDom.innerHTML = r.data;
    					document.body.appendChild(divDom)

    					let testForm = document.getElementsByName('punchout_form')
    					testForm[0].dispatchEvent(new Event('submit'))
    					testForm[0].submit()
    					document.body.removeChild(testForm[0])

    				}
    			//	window.location.href = r;
    				// #endif
    				// #ifdef APP-PLUS
    				uni.requestPayment({
    					provider: 'alipay',
    					orderInfo: r, //微信、支付宝订单数据
    					success: function () {
    						mHelper.toast('充值成功');
    						mRouter.redirectTo({route});
    					},
    					fail: function (err) {
    						console.log(err)
    						mHelper.toast('充值已取消');
    					}
    				});
    				// #endif
    			});
    	},
};
